package com.lagou.edu.factory;

import com.lagou.edu.annotation.Autowired;
import com.lagou.edu.annotation.Service;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.swing.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author sxnan
 * @className ProxyFactory
 * @description TODO
 * @date 2020/6/6
 */
@Service
public class ProxyFactory {
    @Autowired
    private TransactionManager transactionManager;

    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                try {
                    // 开启事务(关闭事务的自动提交)
                    transactionManager.beginTransaction();
                    Object result = method.invoke(obj, args);
                    transactionManager.commit();
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollback();
                    // 抛出异常便于上层servlet捕获
                    throw e;

                }
            }
        });
    }

    public Object getCglibProxy(Object obj) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                try {
                    // 开启事务(关闭事务的自动提交)
                    transactionManager.beginTransaction();
                    Object result = method.invoke(obj, objects);
                    transactionManager.commit();
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollback();
                    // 抛出异常便于上层servlet捕获
                    throw e;
                }
            }
        });
    }
}
